#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <fcntl.h>
#include "logger.h"
#include "buffer.h"
#include <limits.h>

#define MESSAGE_SIZE 1<<7
#define LOG_LEVEL_NAME(l_level) #l_level
int log_fd = 0;
int log_level = INFO;


char *log_name[] = {
	LOG_LEVEL_NAME(INFO),
	LOG_LEVEL_NAME(WARNING),
	LOG_LEVEL_NAME(ERROR)
};

void
log_start (int file_descriptor)
{
	log_fd = file_descriptor;
}

void
log_set_level(int level){
	
	log_level = level;
	if ((log_level < 0) || (log_level > 3))
		log_level = 0;
}

void
log_print (int level,char *filename, int line, const char *fmt, ...)
{

	if (level < log_level)
		return;

	va_list list;
	va_start(list, fmt);
	char* message = malloc(MESSAGE_SIZE);
	time_t event_time;
	time (&event_time);
	
	int message_length = sprintf(message, "%s[%s][line: %d]\t %s ", ctime (&event_time), filename, line,log_name[level]);
	message_length += vsprintf(message+message_length, fmt, list);
	
	struct s_buffer* buffer = buffer_init(log_fd);
	buffer_write(buffer, message, strlen(message));
	buffer_flush(buffer);
	
	va_end(list);	
}

